package com.swu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swu.common.Result;
import com.swu.dto.RuleAddDTO;
import com.swu.dto.RuleQueryDTO;
import com.swu.dto.RuleUpdateDTO;
import com.swu.mapper.ValidationRuleMapper;
import com.swu.po.ValidationRule;
import com.swu.service.IAIService;
import com.swu.service.IValidationRuleService;
import com.swu.service.MedicalRecordValidationService;
import com.swu.vo.ValidationRuleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
 * <p>
 * 病案首页校验规则表 服务实现类
 * </p>
 *
 * @author 勾新杰
 * @since 2025-06-08
 */
@Service
public class ValidationRuleServiceImpl extends ServiceImpl<ValidationRuleMapper, ValidationRule> implements IValidationRuleService {

    private final MedicalRecordValidationService medicalRecordValidationService;
    private final IAIService aiService;

    @Autowired
    public ValidationRuleServiceImpl(@Lazy MedicalRecordValidationService medicalRecordValidationService, IAIService aiService) {
        this.medicalRecordValidationService = medicalRecordValidationService;
        this.aiService = aiService;
    }

    /**
     * 将ValidationRule转换为ValidationRuleVO
     */
    private ValidationRuleVO convertToVO(ValidationRule rule) {
        if (rule == null) {
            return null;
        }
        ValidationRuleVO vo = new ValidationRuleVO();
        BeanUtil.copyProperties(rule, vo);
        return vo;
    }

    @Override
    @Transactional
    public Result<ValidationRuleVO> addRule(RuleAddDTO ruleAddDTO) {
        try {
            // 1. 使用AI生成规则内容
            String ruleContent = StrUtil.isBlank(ruleAddDTO.getRuleContent()) ? aiService.generateDroolsRule(
                    ruleAddDTO.getRuleName(),
                    ruleAddDTO.getRuleDescription()
            ) : ruleAddDTO.getRuleContent();

            // 2. 创建规则对象
            ValidationRule rule = new ValidationRule();
            rule.setRuleName(ruleAddDTO.getRuleName());
            rule.setRuleDescription(ruleAddDTO.getRuleDescription());
            rule.setRuleType(Integer.valueOf(ruleAddDTO.getRuleType()));
            rule.setRuleContent(ruleContent);  // 使用AI生成的规则内容
            rule.setStatus(Integer.valueOf(ruleAddDTO.getStatus()));
            rule.setCreator(ruleAddDTO.getCreator());
            rule.setUpdater(ruleAddDTO.getUpdater());

            // 3. 设置创建和更新时间
            LocalDateTime now = LocalDateTime.now();
            rule.setCreateTime(now);
            rule.setUpdateTime(now);

            // 4. 保存规则
            save(rule);

            // 5. 重新加载规则
            medicalRecordValidationService.reloadRules();

            return Result.success(convertToVO(rule));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加规则失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<ValidationRuleVO> updateRule(RuleUpdateDTO ruleUpdateDTO) {
        try {
            // 检查规则是否存在
            ValidationRule existingRule = getById(ruleUpdateDTO.getId());
            if (existingRule == null) {
                return Result.error("规则不存在");
            }

            // 更新规则信息
            ValidationRule rule = new ValidationRule();
            rule.setId(ruleUpdateDTO.getId());
            rule.setRuleName(ruleUpdateDTO.getRuleName());
            rule.setRuleDescription(ruleUpdateDTO.getRuleDescription());
            rule.setRuleType(Integer.valueOf(ruleUpdateDTO.getRuleType()));
            rule.setRuleContent(ruleUpdateDTO.getRuleContent());
            rule.setStatus(Integer.valueOf(ruleUpdateDTO.getStatus()));
            rule.setUpdater(ruleUpdateDTO.getUpdater());
            rule.setUpdateTime(LocalDateTime.now());

            // 保留原有的创建信息
            rule.setCreateTime(existingRule.getCreateTime());
            rule.setCreator(existingRule.getCreator());

            // 更新规则
            updateById(rule);

            // 重新加载规则
            medicalRecordValidationService.reloadRules();

            return Result.success(convertToVO(rule));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("更新规则失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> deleteRule(Long id) {
        try {
            // 检查规则是否存在
            if (!removeById(id)) {
                return Result.error("规则不存在");
            }

            // 重新加载规则
            medicalRecordValidationService.reloadRules();

            return Result.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("删除规则失败：" + e.getMessage());
        }
    }

    @Override
    public Result<ValidationRule> getRule(Long id) {
        ValidationRule rule = getById(id);
        if (rule == null) {
            return Result.error("规则不存在");
        }
        return Result.success(rule);
    }

    @Override
    public Result<Page<ValidationRuleVO>> listRules(RuleQueryDTO queryDTO) {
        try {
            // 创建分页对象
            Page<ValidationRule> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

            // 构建查询条件
            LambdaQueryWrapper<ValidationRule> queryWrapper = new LambdaQueryWrapper<>();

            // 添加查询条件
            if (StringUtils.hasText(queryDTO.getRuleName())) {
                queryWrapper.like(ValidationRule::getRuleName, queryDTO.getRuleName());
            }
            if (StringUtils.hasText(queryDTO.getRuleType())) {
                queryWrapper.eq(ValidationRule::getRuleType, Integer.valueOf(queryDTO.getRuleType()));
            }
            if (StringUtils.hasText(queryDTO.getStatus())) {
                queryWrapper.eq(ValidationRule::getStatus, Integer.valueOf(queryDTO.getStatus()));
            }

            // 按创建时间降序排序
            queryWrapper.orderByDesc(ValidationRule::getCreateTime);

            // 执行分页查询
            Page<ValidationRule> rulePage = page(page, queryWrapper);

            // 转换为VO对象
            Page<ValidationRuleVO> voPage = new Page<>();
            BeanUtil.copyProperties(rulePage, voPage, "records");
            voPage.setRecords(rulePage.getRecords().stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList()));

            return Result.success(voPage);
        } catch (Exception e) {
            return Result.error("查询规则列表失败：" + e.getMessage());
        }
    }
}
